$(document).ready(function() {

	var projectId = $.getUrlVar('id');
	
	if(projectId == '0'){
		$('#projectHeader').text('New Project');
		$('#deleteButton').hide();
	}
	else {
		$('#projectHeader').text('Project ' + projectId);
		$('#startDate').attr('disabled', 'true');
		$('#iterationLength').attr('disabled', 'true');
	}
});

function calcEndDate(){
	var startDate = $('#startDate').val();
	$('#endDate').val(startDate);
}

function saveProject(){
	
	var projectName = $('#projectName').val();
	var startDate = $('#startDate').val();
	var endDate = $('#endDate').val();
	var iterationLength = $('#iterationLength').val();
	var projectId = $.getUrlVar('id');

	if(projectId == 0){
		$.ajax({
			url: 'backend/create_project.php',
			type: 'post',
			data: {'project_name': projectName, 'start_date': startDate, 
				'end_date': endDate, 'iteration_length': iterationLength},
			success: function(data){
				location.href = "projects.php?id=" + data.project_id;
			},
			error: function(xhr, desc, err){
				console.log(xhr);
			}
		});
	}
	else{
		$.ajax({
			url: "backend/save_project.php",
			type: 'post',
			data: {'project_name': projectName, 'project_id': projectId},
			success: function(data){
				location.href = "projects.php?id=" + data.project_id;
			},
			error: function(xhr, desc, err){
				console.log(xhr);
			}
		});
	}
}

function deleteProject(){
	var projectId = $.getUrlVar('id');
	
	$.ajax({
		url: 'backend/delete_project.php',
		type: 'post',
		data: {'project_id': projectId},
		success: function(data){
			location.href = "home.php";
		},
		error: function(xhr, desc, err){
			console.log(xhr);
		}
	});
}

function linkToIteration(id){
	var iterationId = id;
	
	location.href = "iterations.php?id=" + iterationId;
}

function createIterationAjaxRequest(project_id, strURL, funcCallBack){
	$.ajax({
		url: strURL,
		type: 'post',
		data: {'project_id': project_id },
		success: funcCallBack,
		error: function(xhr, desc, err){
			console.log(xhr);
	        console.log("Details: " + desc + "\nError:" + err);
		}
	});
}	

function funcNewIter(data, status){
	console.log(data.code);
	//If an error occurred, output the error
	if(data.code == "ERROR"){
		displayErrorMessage(data.message);
	} else if(data.code == "SUCCESS"){
		//TODO redirect to home page
		document.location.href = "iterations.php?id="+data.iteration_id;
	}
};
	
function createIteration(){
	var projectId = $.getUrlVar('id');
	console.log(projectId);
	createIterationAjaxRequest(projectId, "backend/createIteration.php", funcNewIter);
}